//
//  GAStream.m
//  testjabber
//
//  Created by imuse on 11-7-8.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "GAStream.h"
#import "GTMBase64.h"

@implementation GAStream

- (void)dealloc {
  [self closeStream];
  if (m_pReadBuffer) {
    free(m_pReadBuffer);
  }
  if (m_pSendData) {
    [m_pSendData release];
  }
}

- (void)setDelegate:(id<GAStreamDelegate>)_d
{
  _delegate = _d;
}

- (void)setServerIPPort:(char*)apServer withPort:(int)anPort
{
  m_pstrServer = [NSString stringWithUTF8String:apServer];
  [m_pstrServer retain];
  m_nPort = anPort;
}

- (void)connectToServer
{
  CFReadStreamRef     readStream = NULL;
  CFWriteStreamRef    writeStream = NULL;
  
  CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                     (CFStringRef)m_pstrServer,
                                     m_nPort,
                                     &readStream,
                                     &writeStream);
  if(readStream && writeStream)
  {
    inStream = (NSInputStream *)readStream;
    outStream = (NSOutputStream *)writeStream;
    [self openStream];
  }
  else
  {
    //创建连接失败
    if (_delegate) {
      [_delegate gaStreamEvent:kGAStreamStatusFailed withData:NULL withDataSize:0];
    }
  }
}

- (void)readData
{
  if (!m_pReadBuffer) {
    m_pReadBuffer = malloc(1032);
  }
  
  int len;
  
  while([inStream hasBytesAvailable])
  {
    memset(m_pReadBuffer, 0, 1032);
    len = [inStream read:m_pReadBuffer maxLength:1024];
    
    if (len > 0)
    {
      //向外通知数据
      if (_delegate) {
        [_delegate gaStreamEvent:kGAStreamStatusData
                        withData:m_pReadBuffer
                    withDataSize:len];
      }
    }
  }
}

- (void)sendTempBufferQueue
{
  if (m_pSendData!=nil && [m_pSendData length]>0) {
    //如果缓冲区中有待发送数据，现在发送。
    int a_nSize;
    char *a_pBuffer;
    a_nSize = [m_pSendData length];
    a_pBuffer = malloc(a_nSize);
    [m_pSendData getBytes:a_pBuffer];
    [m_pSendData setLength:0];
    [self writeBytes:a_pBuffer length:a_nSize];
  }
}

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode 
{
  if (aStream!=inStream && aStream!=outStream) {
    //旧的连接流，直接抛弃
    printf("\n********\naStream!=inStream && aStream!=outStream\n********\n");
    return;
  }
  switch(eventCode) {
    case NSStreamEventHasBytesAvailable:
    {
			[self readData];
    }
      break;
    case NSStreamEventEndEncountered:
    {
       //连接关闭
      [self closeStream];
      if (_delegate) {
        [_delegate gaStreamEvent:kGAStreamStatusClose withData:NULL withDataSize:0];
      }
    }
      break;
    case NSStreamEventHasSpaceAvailable:
    {
      //发送临时缓冲队列
      [self sendTempBufferQueue];
    }
      break;
    case NSStreamEventErrorOccurred:
    {
      //连接出错
      if (aStream==outStream && _delegate) {
        [_delegate gaStreamEvent:kGAStreamStatusError withData:NULL withDataSize:0];
      }
    }
      break;
    case NSStreamEventOpenCompleted:
    {
      //创建连接成功
      if (aStream==outStream && _delegate) {
        [_delegate gaStreamEvent:kGAStreamStatusComplete withData:NULL withDataSize:0];
      }
    }
      break;
    case NSStreamEventNone:
      break;
  }
}

-(void)closeStream{
  if (inStream!=nil) {
    [inStream close];
    [outStream close];
    [inStream removeFromRunLoop:[NSRunLoop currentRunLoop]
                        forMode:NSDefaultRunLoopMode];
    [outStream removeFromRunLoop:[NSRunLoop currentRunLoop]
                         forMode:NSDefaultRunLoopMode];
    [inStream setDelegate:nil];
    [outStream setDelegate:nil];
    [inStream release];
    [outStream release];
    inStream = nil;
    outStream = nil;
  }
}

-(void)openStream{
  [inStream retain];
  [outStream retain];
//  [inStream setProperty:NSStreamSocketSecurityLevelSSLv3 forKey:NSStreamSocketSecurityLevelKey];
//  [outStream setProperty:NSStreamSocketSecurityLevelSSLv3 forKey:NSStreamSocketSecurityLevelKey];
//  NSMutableDictionary * sslSettings;
//  sslSettings = [NSMutableDictionary dictionaryWithObjectsAndKeys:(id)kCFBooleanFalse,kCFStreamSSLValidatesCertificateChain,kCFBooleanFalse,kCFStreamSSLIsServer,nil];
//  CFWriteStreamSetProperty((CFWriteStreamRef)outStream, kCFStreamPropertySSLSettings, sslSettings);
  [inStream setDelegate:self];
  [outStream setDelegate:self];
  [inStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                      forMode:NSDefaultRunLoopMode];
  [outStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                       forMode:NSDefaultRunLoopMode];
  [inStream open];
  [outStream open];
}


- (int)writeBytes:(char*)apSendBuffer length:(unsigned int)anSize
{
//  NSString *str =[NSString stringWithUTF8String:apSendBuffer];
//  NSLog(@"apSendBuffer %@",str);
//  
//  NSLog(@"anSize %d",anSize);
  
  int nLen = 0;
  if ([outStream hasSpaceAvailable]) {
    nLen = [outStream write:(const uint8_t*)apSendBuffer maxLength: anSize];
  }
  
//  NSLog(@"nLen %d",nLen);
  
  if (nLen<anSize) {
    if (m_pSendData==nil) {
      m_pSendData = [[NSMutableData alloc] init];
    }
    
    if (nLen==-1) {
      //出错,缓存所有数据
      [m_pSendData appendBytes:apSendBuffer length:anSize];
      //NSLog(@"\nError:%@ : %@\n",[[outStream streamError] code], [[outStream streamError] localizedDescription]);
    } else {
      //缓存未能发送数据
      [m_pSendData appendBytes:apSendBuffer+nLen length:anSize-nLen];
    }
  }
  return nLen;
} 
@end

